package com.aabte.hystrixlearn.controller;

import com.aabte.hystrixlearn.hystrix.command.GetProductInfoCommand;
import com.aabte.hystrixlearn.hystrix.command.GetProductInfosCommand;
import com.aabte.hystrixlearn.model.ProductInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import rx.Observable;
import rx.Observer;

import java.util.Arrays;

/**
 * @author Daniel
 */
@Slf4j
@RestController
public class CacheController {

    @RequestMapping("/getProductInfo")
    public ProductInfo getProductInfo(
            Long projectId
    ) {
        log.info("Start getProductInfo. projectId: {}", projectId);
        GetProductInfoCommand command = new GetProductInfoCommand(projectId);
        ProductInfo rs = command.execute();
        log.info("End getProductInfo. rs: {}", rs);
        return rs;
    }

    @RequestMapping("/getProductInfos")
    public String getProductInfos(
            Long[] projectIds
    ) {
        log.info("Start getProductInfos. projectIds: {}", Arrays.asList(projectIds));
        GetProductInfosCommand command = new GetProductInfosCommand(projectIds);
        Observable<ProductInfo> observe = command.observe();

        observe.subscribe(new Observer<ProductInfo>() {
            @Override
            public void onCompleted() {
                log.info("getProductInfos.onCompleted");
            }

            @Override
            public void onError(Throwable throwable) {
                log.info("getProductInfos.onError", throwable);
            }

            @Override
            public void onNext(ProductInfo productInfo) {
                log.info("getProductInfos.onNext productInfo: {}", productInfo);
            }
        });
        log.info("End getProductInfos. projectIds: {}", Arrays.asList(projectIds));
        return "success";
    }

}
